/**
 * 
 */
package org.t2.game.server.foundation.starting;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.banish.sql.DaosBooter;
import org.banish.sql.core.annotation.SplitTable;
import org.banish.sql.core.annotation.Table;
import org.banish.sql.core.entity.AbstractEntity;
import org.gaming.ruler.lifecycle.Lifecycle;
import org.gaming.ruler.lifecycle.LifecycleInfo;
import org.gaming.ruler.lifecycle.Ordinal;
import org.gaming.ruler.lifecycle.Priority;
import org.gaming.ruler.spring.Spring;
import org.gaming.service.repository.Repository;
import org.gaming.service.repository.database.DBConfig;
import org.gaming.service.repository.database.MySqlDataSource;
import org.gaming.service.repository.database.JsonFormatter;
import org.gaming.tool.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

/**
 * @author YY
 *
 */
@Component
public class DatabaseLifecycle implements Lifecycle {

	private static Logger logger = LoggerFactory.getLogger(DatabaseLifecycle.class);
	
	@Autowired
	private ApplicationSettings applicationSettings;
	
	@Override
	public LifecycleInfo getInfo() {
		return LifecycleInfo.valueOf(this.getClass().getSimpleName(), Priority.INITIALIZATION, Ordinal.MIN);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void start() throws Exception {
        String dbFilePath = "";
        if(applicationSettings.getDatabaseConfigFile().startsWith("file")) {
            ResourceLoader loader = new DefaultResourceLoader();
            Resource resource = loader.getResource(applicationSettings.getDatabaseConfigFile());
            dbFilePath = resource.getFile().getPath();
        } else {
            dbFilePath = applicationSettings.getDatabaseConfigFile();
        }
        List<DBConfig> dbConfigs = DBConfig.loadConfigs(dbFilePath);
		for(DBConfig dbConfig : dbConfigs) {
			logger.info("加载数据库配置：{}", GsonUtil.toJson(dbConfig));
		}
		
		Collection<Object> entitySamples = Spring.getBeansWithAnnotation(Table.class);
		Collection<Object> logSamples = Spring.getBeansWithAnnotation(SplitTable.class);
		
		List<Class<? extends AbstractEntity>> classList = new ArrayList<>();
		for(Object bean : entitySamples) {
			if (bean instanceof AbstractEntity) {
				classList.add((Class<? extends AbstractEntity>)Spring.getBeanRealClass(bean));
			}
		}
		for(Object bean : logSamples) {
			if (bean instanceof AbstractEntity) {
				classList.add((Class<? extends AbstractEntity>)Spring.getBeanRealClass(bean));
			}
		}
		
		DaosBooter daosBuilder = new DaosBooter(applicationSettings.getGameServerId());
		for(DBConfig dbConfig : dbConfigs) {
			logger.info("加载数据库配置：{}", GsonUtil.toJson(dbConfig));
			daosBuilder.addDataSource(new MySqlDataSource(dbConfig));
		}
		daosBuilder.addEntityClasses(classList);
		daosBuilder.addValueFormater(new JsonFormatter());
		daosBuilder.setup();
		Repository.build(false);
	}

	@Override
	public void stop() throws Exception {
		DaosBooter.stopAsync();
	}
}
